import { useEffect, useState } from "react";
import CommonModal from "@/components/CommonModal";
import { Checkbox, Form, message, Radio, Space } from "antd";
import { againcodeorderstrategyDetail, againcodeorderstrategyUpdate } from "../service";
import CommonInput from "@/pages/OrderModule/common/components/CommonInput";
import IconFont from "@/components/IconFont";
import BatchSuffixInput from "@/views/components/BatchSuffixInput";
import CommonText from "@/pages/OrderModule/common/components/CommonText/CommonText";
import FiledWrapper from "@/pages/OrderModule/orderList/components/Filter/components/FieldWrapper";
import CommonInputNumber from "@/pages/OrderModule/common/components/CommonInputNumber";
import SelectShop from "@/components/SelectShop";
import SelectTag from "@/components/SelectTag";
import { labelTypeMap, labelColorMap } from "@/utils/config";
import { isEmpty, find } from "lodash";

//旗帜🚩
const checkboxList = [
	{
		label: <CommonText extractIcon={<IconFont type="iconqizhihong"></IconFont>} />,
		value: 1
	},
	{
		label: <CommonText extractIcon={<IconFont type="iconqizhihuang"></IconFont>} />,
		value: 2
	},
	{
		label: <CommonText extractIcon={<IconFont type="iconqizhilv"></IconFont>} />,
		value: 3
	},
	{
		label: <CommonText extractIcon={<IconFont type="iconqizhilan"></IconFont>} />,
		value: 4
	},

	{
		label: <CommonText extractIcon={<IconFont type="iconqizhizi"></IconFont>} />,
		value: 5
	}
];

/** 不参与重匹配的订单范围  */
const OrderRangeModal = ({ handleCancel }) => {
	const [selectShops, setSelectShops] = useState([]); //选择的店铺
	const [shopVisible, setShopVisible] = useState(false); //店铺组件弹窗
	const [labelVisible, setLabelVisible] = useState(false); //是否展示标签弹窗
	const [selectLabels, setSelectLabels] = useState([]); //选择订单标签
	const [detailData, setDetailData] = useState({}); //详情数据
	const [isOk, setIsOk] = useState(false);
	const [open, setOpen] = useState(false);

	const [form] = Form.useForm();

	const labelRule = Form.useWatch("labelRule", form);
	const buyerMessageRule = Form.useWatch("buyerMessageRule", form);
	const sellerMessageRule = Form.useWatch("sellerMessageRule", form);
	const flagRule = Form.useWatch("flagRule", form);

	useEffect(() => {
		setOpen(true);
		form.resetFields();
		getAgaincodeorderstrategyDetail();
	}, []);

	useEffect(() => {
		if (!isEmpty(detailData)) {
			form.resetFields();
			if (detailData.labelConfigList) {
				setSelectLabels(detailData.labelConfigList);
			}
			if (detailData.ecStoreList) {
				setSelectShops(detailData.ecStoreList);
			}
		}
	}, [detailData]);

	useEffect(() => {
		if (selectShops.length) {
			form.setFieldsValue({
				ecStoreIds: selectShops.map(item => (item.systemStoreName ? item.systemStoreName : item.storeName)).join(",")
			});
		} else {
			form.setFieldsValue({ ecStoreIds: "" });
		}
	}, [selectShops]);

	useEffect(() => {
		if (selectLabels.length) {
			console.log("selectLabels123", selectLabels);
			form.setFieldsValue({
				labelIds: selectLabels.map(item => (labelTypeMap[item.name] ? labelColorMap[item.name] : item.name)).join(",")
			});
		} else {
			form.setFieldsValue({ labelIds: "" });
		}
	}, [selectLabels]);

	//查询订单范围详情
	const getAgaincodeorderstrategyDetail = async () => {
		START_LOADING();
		const { success, data = {} } = await againcodeorderstrategyDetail();
		if (success) {
			setDetailData(data);
		}
		END_LOADING();
	};

	//保存订单范围
	const handleAgaincodeorderstrategyUpdate = async val => {
		console.log("handleAgaincodeorderstrategyUpdate", val);
		START_LOADING();
		const params = {
			...val,
			ecStoreIds: selectShops.length > 0 ? selectShops.map(item => item.id).join(",") : undefined,
			labelIds: selectLabels.length > 0 ? selectLabels.map(item => item.id).join(",") : undefined,
			flags: val.flags && val.flags.join(","),
			id: detailData.id
		};
		const { success, msg = "操作成功" } = await againcodeorderstrategyUpdate(params);
		if (success) {
			message.success(msg);
			setIsOk(true);
			setOpen(false);
		}
		END_LOADING();
	};

	//清除店铺/标签弹窗
	const handleClear = (e, code) => {
		const val = e.target.value;
		if (val == "") {
			if (code == "store") {
				setSelectShops([]);
			}
		}
	};

	const renderNumberArea = () => {
		const renderInputNumber = (label, field1, field2) => {
			const numberInputProps = { controls: false, min: 0, placeholder: "请输入" };
			const minValue = form.getFieldValue(field1),
				maxValue = form.getFieldValue(field2);
			return (
				<>
					<FiledWrapper
						label={label}
						labelHigh={minValue || maxValue ? true : false}
						childrenStyle={{ display: "flex" }}
						style={{ marginTop: 16, paddingLeft: 12 }}
					>
						<Form.Item name={field1} noStyle>
							<CommonInputNumber {...numberInputProps} />
						</Form.Item>
						<i className="connector" />
						<Form.Item name={field2} noStyle>
							<CommonInputNumber {...numberInputProps} />
						</Form.Item>
					</FiledWrapper>
				</>
			);
		};

		return (
			<>
				<div style={{ marginTop: "16px" }}></div>
				{renderInputNumber("订单金额", "minOrderAmount", "maxOrderAmount")}
				{renderInputNumber("订单重量", "minOrderWeight", "maxOrderWeight")}
				<div style={{ marginBottom: 16 }}></div>
			</>
		);
	};

	//点击确定
	const onOk = () => {
		form
			.validateFields()
			.then(val => {
				handleAgaincodeorderstrategyUpdate(val);
			})
			.catch(err => {
				console.log(err, "err");
			});
	};

	const onCancel = () => {
		setOpen(false);
	};

	const afterClose = () => {
		if (isOk) {
			handleCancel();
		} else {
			handleCancel();
		}
	};

	//店铺组件
	const SelectShopProps = {
		selectShops: selectShops.map(item => item.id),
		handleCancel() {
			setShopVisible(false);
		},
		handleOk(arr) {
			setShopVisible(false);
			setSelectShops(arr);
		}
	};

	//标签弹窗
	const SelectTagProps = {
		selectLabels: selectLabels.map(item => item.id),
		showFilterMethod: false,
		handleCancel() {
			setLabelVisible(false);
		},
		handleDealData(selectTag, realData) {
			const arr = [];
			selectTag.forEach(item => {
				const obj = find(realData, ["id", item]);
				arr.push(obj);
			});
			console.log("handleDealData", selectTag, realData, arr);
			return arr;
		},
		handleOK(val) {
			setLabelVisible(false);
			setSelectLabels(val);
		}
	};

	return (
		<CommonModal title="参与重匹配的订单范围" afterClose={afterClose} open={open} width="520px" onOk={onOk} onCancel={onCancel}>
			<Form
				name="basic"
				onFinish={onOk}
				form={form}
				autoComplete="off"
				layout="horizontal"
				labelAlign="right"
				initialValues={{
					...detailData,
					flags: detailData.flags ? detailData.flags.split(",") : undefined
				}}
			>
				<Form.Item name="ecStoreIds">
					<CommonInput
						// {...inputProps}
						// readOnly
						allowClear
						onClick={() => setShopVisible(true)}
						onChange={e => handleClear(e, "store")}
						placeholder="请选择店铺"
						style={{ width: "200px" }}
						suffix={<IconFont onClick={() => setShopVisible(true)} style={{ cursor: "pointer" }} type="iconmodal-input" />}
					/>
				</Form.Item>
				<Form.Item name="buyerMessageRule" label="买家留言">
					<Radio.Group>
						<Radio value={1}>不判断</Radio>
						<Radio value={2}>有留言</Radio>
						<Radio value={3}>包含以下留言</Radio>
					</Radio.Group>
				</Form.Item>
				{buyerMessageRule == 3 ? (
					<Form.Item name="buyerMessage" wrapperCol={{ offset: 2 }}>
						<BatchSuffixInput
							clearable
							allowClear
							autoMultiLine
							modalProps={{
								title: "批量输入"
							}}
							maxItem={500}
							placeholder="请输入留言备注关键字，多个逗号隔开"
							message="分行输入内容，提交后主页面输入框会按照逗号自动隔开，点击查询可批量查询。"
							areaPlaceholder="每行输入1个内容，最多500个，例如:&#10;1272572508553111112223&#10;1272572512332111112226"
						/>
					</Form.Item>
				) : (
					""
				)}
				<Form.Item name="sellerMessageRule" label="卖家备注">
					<Radio.Group>
						<Radio value={1}>不判断</Radio>
						<Radio value={2}>有备注</Radio>
						<Radio value={3}>包含以下备注</Radio>
					</Radio.Group>
				</Form.Item>
				{sellerMessageRule == 3 ? (
					<Form.Item name="sellerMessage" wrapperCol={{ offset: 2 }}>
						<BatchSuffixInput
							clearable
							allowClear
							autoMultiLine
							modalProps={{
								title: "批量输入"
							}}
							maxItem={500}
							placeholder="请输入留言备注关键字，多个逗号隔开"
							message="分行输入内容，提交后主页面输入框会按照逗号自动隔开，点击查询可批量查询。"
							areaPlaceholder="每行输入1个内容，最多500个，例如:&#10;1272572508553111112223&#10;1272572512332111112226"
						/>
					</Form.Item>
				) : (
					""
				)}
				<Form.Item name="flagRule" label="旗帜" style={{ marginLeft: "28px" }}>
					<Radio.Group>
						<Radio value={1}>不判断</Radio>
						<Radio value={2}>有旗帜</Radio>
						<Radio value={3}>包含以下旗帜</Radio>
					</Radio.Group>
				</Form.Item>
				{flagRule == 3 ? (
					<Form.Item name="flags" wrapperCol={{ offset: 2 }}>
						<Checkbox.Group style={{ width: "100%" }}>
							<Space direction="horizontal">
								{checkboxList.map(item => (
									<Checkbox key={item.value} value={item.value + ""}>
										{item.label}
									</Checkbox>
								))}
							</Space>
						</Checkbox.Group>
					</Form.Item>
				) : (
					""
				)}
				<Form.Item name="labelRule" label="订单标签" colon>
					<Radio.Group>
						<Radio value={1}>不判断</Radio>
						<Radio value={2}>有标签</Radio>
						<Radio value={3}>包含以下标签</Radio>
					</Radio.Group>
				</Form.Item>
				{labelRule == 3 ? (
					<Form.Item name="labelIds" wrapperCol={{ offset: 2 }}>
						<CommonInput
							// readOnly
							allowClear
							onClick={() => setLabelVisible(true)}
							onChange={e => handleClear(e, "orderTag")}
							placeholder="请选择订单标签"
							suffix={<IconFont onClick={() => setLabelVisible(true)} style={{ cursor: "pointer" }} type="iconmodal-input" />}
						/>
					</Form.Item>
				) : (
					""
				)}
				{renderNumberArea()}
				<Form.Item name="outUniqueCodeRule" label="是否有外部唯一码">
					<Radio.Group>
						<Radio value={1}>不判断</Radio>
						<Radio value={2}>有外部唯一码</Radio>
						<Radio value={3}>无外部唯一码</Radio>
					</Radio.Group>
				</Form.Item>
			</Form>
			{shopVisible && <SelectShop {...SelectShopProps} />}
			{labelVisible && <SelectTag {...SelectTagProps} />}
		</CommonModal>
	);
};

export default OrderRangeModal;
